"""React智能体-数学计算"""
import sympy

from typing import Type, Optional
from langchain_core.tools import BaseTool
from pydantic import BaseModel, Field
from langchain_core.callbacks import (
    AsyncCallbackManagerForToolRun,
    CallbackManagerForToolRun,
)

from .tool_result import ToolResult


class CalculatorInput(BaseModel):
    expression: str = Field(description="待计算的数学表达式")
    n: int = Field(default=15, description="精确到小数点后多少位")

class CalculatorTool(BaseTool):
    name: str = 'calculator'
    description: str = "可快速精准完成复杂数学表达式的数值计算，方便获取近似计算结果。"
    args_schema: Type[BaseModel] = CalculatorInput.model_json_schema()
    return_direct: bool = True

    def _run(self, expression: str, n: int = 15,
        run_manager: Optional[CallbackManagerForToolRun] = None
    ) -> ToolResult:
        """执行数学计算"""
        try:
            expression = expression.strip()
            result = float(sympy.N(expression, n))

            return ToolResult(
                success=True,
                data=result,
                metadata={"type": "Calculation"}
            )

        except Exception as e:
            return ToolResult(
                success=False,
                data=None,
                error=f"Calculation failed: {str(e)}"
            )

    async def _arun(
        self,
        expression: str, n: int = 15,
        run_manager: Optional[AsyncCallbackManagerForToolRun] = None
    ) -> ToolResult:
        """执行数学计算"""
        return self._run(expression, n, run_manager=run_manager.get_sync())



if __name__ == '__main__':
    tool_case = CalculatorTool()
    print(tool_case.name)
    print(tool_case.description)
    print(tool_case.args)
    print(tool_case.run('(sin(3) + log(3)) / ( 1 + sqrt(5) + exp(1))'))
